
package guice.boot.archive.container.service.biz;

import guice.boot.archive.common.log.Logger;
import guice.boot.archive.common.log.LoggerFactory;
import guice.boot.archive.exception.ArkRuntimeException;
import guice.boot.archive.spi.model.Biz;
import guice.boot.archive.spi.service.ArkInject;
import guice.boot.archive.spi.service.biz.BizDeployer;
import guice.boot.archive.spi.service.biz.BizManagerService;

/**
 * Biz Deployer to deploy Biz
 */
public class DefaultBizDeployer implements BizDeployer {

    private static final Logger LOGGER = LoggerFactory.getDefaultLogger();
    @ArkInject
    private BizManagerService bizManagerService;
    private String[] arguments;

    @Override
    public void init(String[] args) {
        this.arguments = args;
    }

    @Override
    public void deploy() {
        for (Biz biz : bizManagerService.getBizInOrder()) {
            try {
                LOGGER.info(String.format("Begin to start biz: %s", biz.getBizName()));
                biz.start(arguments);
                LOGGER.info(String.format("Finish to start biz: %s", biz.getBizName()));
            } catch (Throwable e) {
                LOGGER.error(String.format("Start biz: %s meet error", biz.getBizName()), e);
                throw new ArkRuntimeException(e);
            }
        }
    }

    @Override
    public void unDeploy() {
        for (Biz biz : bizManagerService.getBizInOrder()) {
            try {
                LOGGER.info(String.format("Begin to stop biz: %s", biz.getBizName()));
                biz.stop();
                LOGGER.info(String.format("Finish to stop biz: %s", biz.getBizName()));
            } catch (Throwable e) {
                LOGGER.error(String.format("stop biz: %s meet error", biz.getBizName()), e);
                throw new ArkRuntimeException(e);
            }
        }
    }

    @Override
    public String getDesc() {
        return String.format("{name=\'%s\', provider=\'%s\'}", "DefaultBizDeployer",
                "Ark Container");
    }

}